#include "main.h"
#include <QTimer>
#include <QDir>
#include <QMenu>
#include <QApplication>
#include <QStandardPaths>
#include <QTcpServer>
#include <QTcpSocket>
#include <iostream>
#include "streammanager.h"

Main::Main()
    : m_start(QTime::currentTime()), m_encoder(QSize(1920, 1080))
{
    m_pTcpServer = new QTcpServer(this);
    //2. 新连接、错误信号
    connect(m_pTcpServer, &QTcpServer::newConnection, this, &Main::encode);
    //3. 启动服务端
    if (!m_pTcpServer->listen(QHostAddress::Any, 8888))
    {
        std::cerr << "m_pTcpServer->listen() error";
        exit(-1);
    }
    std::cerr << "listening...";
}

void Main::encode()
{
    //获取与客户端通信的socket
    QTcpSocket* pClientConnection = m_pTcpServer->nextPendingConnection();

    QByteArray bits = m_encoder.getFlvHeader();
    QByteArray inbits1, inbits2;
    QByteArray outbits1, outbits2;

    while (pClientConnection->isOpen()){
        inbits1 = m_encoder.getSequenceHeader();
        to_h264(inbits1.data(), inbits1.size(), outbits1);
        std::cerr << "inbits1 " << inbits1.size() << std::endl;
        std::cerr << "outbits1: " << outbits1.size() << std::endl;
        BlockWriter(pClientConnection).stream() << outbits1;

        // TODO the PTS valuse here are SOOOOOO wrong!
        QImage video = m_encoder.doGrabFrame();
        inbits2 = m_encoder.getEncodedFrame(video, m_videoPts);
        if (inbits2.size() > 0){
            outbits2.clear();
            to_h264(inbits2.data(), inbits2.size(), outbits2);
            std::cerr << "inbits2: " << inbits2.size() << std::endl;
            std::cerr << "outbits2: " << outbits2.size() << std::endl;
            BlockWriter(pClientConnection).stream() << outbits2;
            pClientConnection->flush();
        }
    }
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Main main;
    return a.exec();
}
